package com.example.sherlockzhong.plush_v2;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sherlockzhong.plush_v2.Components.scrolls.AutoScroll;
import com.example.sherlockzhong.plush_v2.Constants.SystemConstant;
import com.example.sherlockzhong.plush_v2.View.MainContentFrame;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

public class MainActivity extends Activity {

    // self
    public MainActivity self = this;

    // main content frame
    public MainContentFrame main_content_frame;
    //用于详细卡片信息的组件
    public LinearLayout ll_detail_weather;
    public ImageView iv_weather;
    public TextView tv_weather_city;
    public TextView tv_weather_top_1;
    public TextView tv_weather_top_2;
    public TextView tv_temperature;
    public TextView tv_small_1;
    public TextView tv_small_2;
    public TextView tv_small_3;
    public TextView tv_small_4;
    public TextView tv_yellow_1;
    public TextView tv_yellow_2;
    public TextView tv_yellow_3;
    public TextView tv_yellow_4;
    public LinearLayout ll_detail_three;
    public TextView tv_detail_title;
    public TextView tv_detail_time;
    public TextView tv_detail_content;
    //万恶 的课程表
    public LinearLayout ll_detail_class;
    public TextView tv_detail_class1;
    public TextView tv_detail_class2;
    public TextView tv_detail_class3;
    public TextView tv_detail_class4;
    public TextView tv_detail_class5;
    public TextView tv_detail_class6;
    public TextView tv_detail_classroom1;
    public TextView tv_detail_classroom2;
    public TextView tv_detail_classroom3;
    public TextView tv_detail_classroom4;
    public TextView tv_detail_classroom5;
    public TextView tv_detail_classroom6;
    public TextView tv_detail_teacher1;
    public TextView tv_detail_teacher2;
    public TextView tv_detail_teacher3;
    public TextView tv_detail_teacher4;
    public TextView tv_detail_teacher5;
    public TextView tv_detail_teacher6;
    public TextView tv_detail_classTime1;
    public TextView tv_detail_classTime2;
    public TextView tv_detail_classTime3;
    public TextView tv_detail_classTime4;
    public TextView tv_detail_classTime5;
    public TextView tv_detail_classTime6;
    public MainController controller;
    public ScrollView sv_cards;
    public LinearLayout ll_detail;
    public LinearLayout ll_setting;
    public LinearLayout ll_about;
    public LinearLayout ll_cover;
    public FrameLayout ll_main;
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {// 此方法在ui线程运行
            super.handleMessage(msg);
            try {
                if (msg.what == 1) {
                    MainActivity.this.reflashDone();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    public Handler keyBackHandler = new Handler();
    //菊花
    private ProgressDialog pd;
    private ImageButton btn_collection;
    private ImageButton btn_setting;
    private ImageButton btn_subscribe;
    private ImageButton btn_title;
    private Button btn_setting_done;
    private Button btn_setting_sync;
    private RelativeLayout btn_setting_lesson_alertTime;
    private RelativeLayout btn_setting_exam_alertTime;
    private RelativeLayout btn_setting_lesson_remind_frame;
    private RelativeLayout btn_setting_exam_remind_frame;
    private Button btn_setting_checkUpdata;
    private Button btn_setting_report;
    private Button btn_setting_aboutUs;
    private Button btn_setting_logout;
    private SeekBar lesson_seeker_bar;
    private TextView lesson_seeker_text;
    private SeekBar exam_seeker_bar;
    private TextView exam_seeker_text;
    // 标记
    public boolean keyBackPressed = false;
    public boolean refresh = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        try {
            getWindow().addFlags(WindowManager.LayoutParams.class.getField("FLAG_NEEDS_MENU_KEY").getInt(null));
        }catch (Exception e) {
            e.printStackTrace();
        }

        this.initWidgets();
        this.controller.testNotification();
//        this.controller.pressTitle(btn_title);

        SharedPreferences sp = getSharedPreferences("user", Context.MODE_PRIVATE);
        if (!sp.getString("studentID", "").equalsIgnoreCase("") && !sp.getString("token", "").equalsIgnoreCase("")) {
            Constant.STUDENT_ID = sp.getString("studentID", "");
            Constant.STUDENT_TOKEN = sp.getString("token", "");
            Constant.ECARD_VERIFIED = sp.getBoolean("ecardVerified", false);
            if (sp.getInt("classWarningTime", -1) == -1) {
                SharedPreferences.Editor editor = sp.edit();
                editor.putInt("classWarningTime", 45);
                editor.putInt("examWarningTime", 15);
                editor.commit();
                Constant.EXAM_WARNING_TIME = 15;
                Constant.CLASS_WARNING_TIME = 45;
            } else {
                Constant.EXAM_WARNING_TIME = sp.getInt("examWarningTime", 15);
                Constant.CLASS_WARNING_TIME = sp.getInt("classWarningTime", 45);
            }
            lesson_seeker_bar.setProgress(Constant.CLASS_WARNING_TIME / 15 - 1);
            lesson_seeker_text.setText(Constant.CLASS_WARNING_TIME + "分钟");
            exam_seeker_bar.setProgress(Constant.EXAM_WARNING_TIME / 5 - 1);
            exam_seeker_text.setText(Constant.EXAM_WARNING_TIME + "天");
        }

        UmengUpdateAgent.update(this);
        MobclickAgent.updateOnlineConfig(this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        this.controller.onTouch(event);
        return super.onTouchEvent(event);
    }

    @Override
    public void onPause() {
        //this.controller.saveCardData();
        if(SystemConstant.voicePlayer!=null) {
            SystemConstant.voicePlayer.stop();
            SystemConstant.voicePlayer.release();
            SystemConstant.voicePlayer = null;
        }
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        AutoScroll autoScroll = (AutoScroll) findViewById(R.id.main_scroll);
        autoScroll.setApp(this);
        autoScroll.setApp(this);
        MobclickAgent.onResume(this);
        if (refresh) {
            System.out.println("refresh");
            this.controller.pressTitle(btn_title);
        } else {
            refresh = true;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0 && resultCode == 0) {
            try {
                Bundle data = intent.getExtras();
                this.refresh = data.getBoolean("refresh");//得到新Activity 关闭后返回的数据
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onRestart() {
        super.onRestart();
    }

    @Override
    public void onStop() {
        //this.controller.saveCardData();
        super.onStop();
    }

    @Override
    public void onDestroy() {
//        this.controller.saveCardData();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            MainActivity.this.pressTitle(btn_title);
        } else if (id == R.id.action_subscribe) {
            MainActivity.this.pressSubscribe(btn_subscribe);
        } else if (id == R.id.action_settings) {
            MainActivity.this.pressSetting(btn_setting);
        } else if (id == R.id.action_collection) {
            MainActivity.this.controller.pressCollection(btn_collection);
        } else {
            return super.onOptionsItemSelected(item);
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (this.controller.isDetail) {
                this.controller.showCards();
            } else {
                if (!keyBackPressed) {
                    keyBackPressed = true;
                    Toast.makeText(MainActivity.this, "再按一次后退键将会退出", Toast.LENGTH_SHORT).show();
                    keyBackHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            keyBackPressed = false;
                        }
                    }, 3000);
                } else {
                    self.finish();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化所有组件
     */
    private void initWidgets() {
        this.controller = new MainController(this);
        MainController.SCALE = getResources().getDisplayMetrics().density;
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        this.main_content_frame = (MainContentFrame) this.findViewById(R.id.main_content_frame);
        this.controller.width = metric.widthPixels;
        this.sv_cards = (ScrollView) findViewById(R.id.main_scroll);
        this.btn_setting = (ImageButton) findViewById(R.id.btn_setting);
        this.btn_title = (ImageButton) findViewById(R.id.btn_title);
        this.btn_subscribe = (ImageButton) findViewById(R.id.btn_subscribe);
        this.btn_setting_done = (Button) findViewById(R.id.btn_setting_done);
        this.btn_collection = (ImageButton) findViewById(R.id.btn_collection);

        //设置的按钮们以及隐藏的seekBar
        this.btn_setting_aboutUs = (Button) findViewById(R.id.btn_setting_aboutUs);
        this.btn_setting_lesson_alertTime = (RelativeLayout) findViewById(R.id.btn_setting_lesson_alertTime);
        this.btn_setting_exam_alertTime = (RelativeLayout) findViewById(R.id.btn_setting_exam_alertTime);
        this.btn_setting_checkUpdata = (Button) findViewById(R.id.btn_setting_checkUpdata);
        this.btn_setting_logout = (Button) findViewById(R.id.btn_setting_logout);
        this.btn_setting_sync = (Button) findViewById(R.id.btn_setting_sync);
        this.btn_setting_report = (Button) findViewById(R.id.btn_setting_report);
        this.btn_setting_lesson_remind_frame = (RelativeLayout) findViewById(R.id.lesson_remind_frame);
        this.btn_setting_exam_remind_frame = (RelativeLayout) findViewById(R.id.exam_remind_frame);

        this.lesson_seeker_text = (TextView) findViewById(R.id.lesson_time);
        this.lesson_seeker_bar = (SeekBar) findViewById(R.id.lesson_remind);
        lesson_seeker_text.setText(Constant.CLASS_WARNING_TIME + "分钟");
        this.exam_seeker_text = (TextView) findViewById(R.id.exam_time);
        this.exam_seeker_bar = (SeekBar) findViewById(R.id.exam_remind);
        exam_seeker_text.setText(Constant.EXAM_WARNING_TIME + "天");


        //天气卡片详细信息
        this.ll_detail_weather = (LinearLayout) findViewById(R.id.ll_detail_weather);
        this.iv_weather = (ImageView) findViewById(R.id.iv_weather);
        this.tv_small_1 = (TextView) findViewById(R.id.tv_small_1);
        this.tv_small_2 = (TextView) findViewById(R.id.tv_small_2);
        this.tv_small_3 = (TextView) findViewById(R.id.tv_small_3);
        this.tv_small_4 = (TextView) findViewById(R.id.tv_small_4);
        this.tv_temperature = (TextView) findViewById(R.id.tv_temperature);
        this.tv_weather_top_1 = (TextView) findViewById(R.id.tv_weather_top_1);
        this.tv_weather_top_2 = (TextView) findViewById(R.id.tv_weather_top_2);
        this.tv_yellow_1 = (TextView) findViewById(R.id.tv_yellow_1);
        this.tv_yellow_2 = (TextView) findViewById(R.id.tv_yellow_2);
        this.tv_yellow_3 = (TextView) findViewById(R.id.tv_yellow_3);
        this.tv_yellow_4 = (TextView) findViewById(R.id.tv_yellow_4);
        this.tv_weather_city = (TextView) findViewById(R.id.tv_weather_city);
        //三行字的卡片的详细信息
        this.ll_detail_three = (LinearLayout) findViewById(R.id.ll_detail_three);
        this.tv_detail_title = (TextView) findViewById(R.id.tv_detail_title);
        this.tv_detail_time = (TextView) findViewById(R.id.tv_detail_time);
        this.tv_detail_content = (TextView) findViewById(R.id.tv_detail_content);

        ll_detail = (LinearLayout) findViewById(R.id.ll_detail);
        ll_setting = (LinearLayout) findViewById(R.id.ll_setting);
        ll_about = (LinearLayout) findViewById(R.id.ll_about);
        ll_main = (FrameLayout) findViewById(R.id.ll_main);
        ll_cover = (LinearLayout) findViewById(R.id.ll_cover);

        //万恶的课程表
        this.ll_detail_class = (LinearLayout) findViewById(R.id.ll_detail_class);
        this.tv_detail_class1 = (TextView) findViewById(R.id.tv_detail_class1);
        this.tv_detail_class2 = (TextView) findViewById(R.id.tv_detail_class2);
        this.tv_detail_class3 = (TextView) findViewById(R.id.tv_detail_class3);
        this.tv_detail_class4 = (TextView) findViewById(R.id.tv_detail_class4);
        this.tv_detail_class5 = (TextView) findViewById(R.id.tv_detail_class5);
        this.tv_detail_class6 = (TextView) findViewById(R.id.tv_detail_class6);
        this.tv_detail_classroom1 = (TextView) findViewById(R.id.tv_detail_classroom1);
        this.tv_detail_classroom2 = (TextView) findViewById(R.id.tv_detail_classroom2);
        this.tv_detail_classroom3 = (TextView) findViewById(R.id.tv_detail_classroom3);
        this.tv_detail_classroom4 = (TextView) findViewById(R.id.tv_detail_classroom4);
        this.tv_detail_classroom5 = (TextView) findViewById(R.id.tv_detail_classroom5);
        this.tv_detail_classroom6 = (TextView) findViewById(R.id.tv_detail_classroom6);
        this.tv_detail_classTime1 = (TextView) findViewById(R.id.tv_detail_classTime1);
        this.tv_detail_classTime2 = (TextView) findViewById(R.id.tv_detail_classTime2);
        this.tv_detail_classTime3 = (TextView) findViewById(R.id.tv_detail_classTime3);
        this.tv_detail_classTime4 = (TextView) findViewById(R.id.tv_detail_classTime4);
        this.tv_detail_classTime5 = (TextView) findViewById(R.id.tv_detail_classTime5);
        this.tv_detail_classTime6 = (TextView) findViewById(R.id.tv_detail_classTime6);
        this.tv_detail_teacher1 = (TextView) findViewById(R.id.tv_detail_teacher1);
        this.tv_detail_teacher2 = (TextView) findViewById(R.id.tv_detail_teacher2);
        this.tv_detail_teacher3 = (TextView) findViewById(R.id.tv_detail_teacher3);
        this.tv_detail_teacher4 = (TextView) findViewById(R.id.tv_detail_teacher4);
        this.tv_detail_teacher5 = (TextView) findViewById(R.id.tv_detail_teacher5);
        this.tv_detail_teacher6 = (TextView) findViewById(R.id.tv_detail_teacher6);

        AutoScroll autoScroll = (AutoScroll) findViewById(R.id.main_scroll);
        autoScroll.setApp(this);
        this.btn_collection.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.this.controller.pressCollection(view);
            }
        });

        this.ll_about.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Animation fadeOut = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fade_out);
                ll_about.startAnimation(fadeOut);
                ll_about.setVisibility(View.GONE);
            }
        });

        this.btn_setting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                MainActivity.this.pressSetting(arg0);
            }
        });
        this.btn_title.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                MainActivity.this.pressTitle(arg0);
            }
        });
        this.btn_subscribe.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                MainActivity.this.pressSubscribe(arg0);
            }
        });
        this.btn_setting_done.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.this.pressSettingDone(view);
            }
        });
        this.btn_setting_aboutUs.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.this.controller.setting_aboutUs();
            }
        });
        this.btn_setting_lesson_alertTime.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (btn_setting_lesson_remind_frame.getVisibility() == View.GONE) {
                    btn_setting_lesson_remind_frame.setVisibility(View.VISIBLE);
                } else {
                    btn_setting_lesson_remind_frame.setVisibility(View.GONE);
                }
            }
        });
        this.btn_setting_exam_alertTime.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (btn_setting_exam_remind_frame.getVisibility() == View.GONE) {
                    btn_setting_exam_remind_frame.setVisibility(View.VISIBLE);
                } else {
                    btn_setting_exam_remind_frame.setVisibility(View.GONE);
                }
            }
        });
        this.btn_setting_checkUpdata.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.this.controller.setting_checkUpdata();
            }
        });
        this.btn_setting_logout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.this.controller.setting_logout();
            }
        });
        this.btn_setting_report.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.this.controller.setting_report();
            }
        });
        this.btn_setting_sync.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.this.controller.setting_sync();
            }
        });

        lesson_seeker_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Integer pro = new Integer((progress + 1) * 15);
                lesson_seeker_text.setText(pro.toString() + "分钟");
                MainActivity.this.controller.setting_lesson_alertTime(pro);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        exam_seeker_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Integer pro = new Integer((progress + 1) * 5);
                exam_seeker_text.setText(pro.toString() + "天");
                MainActivity.this.controller.setting_exam_alertTime(pro);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

//        this.controller.test(this,this.getApplicationContext());

    }

    /**
     * 按下按钮
     */
    private void pressSetting(View v) {
        this.controller.pressSetting(v);
    }

    /**
     * 按下按钮
     */
    public void pressTitle(View v) {
        this.controller.pressTitle(v);
    }

    /**
     * 按下按钮
     */
    private void pressSubscribe(View v) {
        btn_setting_lesson_remind_frame.setVisibility(View.GONE);
        btn_setting_exam_remind_frame.setVisibility(View.GONE);
        this.controller.pressSubscribe(v);
    }

    /**
     * 停止请求
     */
    private void stopRequest() {
        this.controller.stopRequest();
    }

    /**
     * 刷新完获取信息
     */
    private void reflashDone() {
        this.controller.reflashDone();
    }

    /**
     * 按下按钮
     */
    private void pressSettingDone(View v) {
        this.controller.pressSettingDone(v);
    }

    /**
     * 显示刷新的时候的等待进度条
     */
    public void showReflashDialog(String msg) {
        this.pd = new ProgressDialog(this);
        this.pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        this.pd.setCancelable(false);
        this.pd.setMessage(msg);
        this.pd.show();
    }

    /**
     * 结束刷新的时候的等待进度条
     */

    public void stopReflashDialog() {
        if (this.pd != null) {
            pd.dismiss();
        }
    }

    public void onDestory() {
        super.onDestroy();
        stopReflashDialog();
    }

}

